package util

import (
	"fmt"
	ContentResponse "go-toy/constant/response"

	"github.com/gin-gonic/gin"
)

type ResponseContent struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

type ResponseInterface interface {
	ResponseBody(code int, message string, data any) ResponseContent
	ResponseSuccess(c *gin.Context, data any)
	ResponseFailure(c *gin.Context, code int, msg string)
}

// Implements the ResponseInterface interface.
type ResponseBuilder struct {
}

// Returns a normal response
func (r ResponseBuilder) ResponseBody(code int, message string, data any) ResponseContent {
	rc := ResponseContent{
		Code: code,
		Msg:  message,
	}
	if data != nil {
		rc.Data = data
	}
	return rc
}

// Returns a success response
func (r ResponseBuilder) ResponseSuccess(c *gin.Context, data any) {
	c.JSON(
		200,
		r.ResponseBody(
			ContentResponse.CODE_SUCCESS,
			ContentResponse.ResponseCode2Msg(ContentResponse.CODE_SUCCESS),
			data,
		),
	)
}

// Returns a failure response
func (r ResponseBuilder) ResponseFailure(c *gin.Context, code int, msg string) {
	msgPrefix := ContentResponse.ResponseCode2Msg(code)
	if msg != "" {
		msg = fmt.Sprintf("%s[%s]", msgPrefix, msg)
	}
	c.JSON(
		200,
		r.ResponseBody(
			code,
			msg,
			nil,
		),
	)
}

// Global instance of the ResponseInterface interface.
var Response ResponseInterface = ResponseBuilder{}
